import os

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt

from util import output_path, project_path


def plot_weather(name, data):
    if not data:
        return None
    font_prop = FontProperties(fname=os.path.join(project_path,'灵动指书手机字体.ttf'))

    dates = [d['date'][4:] for d in data]
    obs_highs = [d['high'] if d['type'] == 'obs' else None for d in data]
    obs_lows = [d['low'] if d['type'] == 'obs' else None for d in data]
    pred_highs = [d['high'] if d['type'] == 'pred' else None for d in data]
    pred_lows = [d['low'] if d['type'] == 'pred' else None for d in data]
    hist_highs = [d['hist_high'] for d in data]  # 历史高温
    hist_lows = [d['hist_low'] for d in data]    # 历史低温

    plt.figure(figsize=(14, 7))

    # 绘制实测数据（实线）
    plt.plot(dates, obs_highs, label='实测高温', marker='o', color='red', linestyle='-', linewidth=2)
    plt.plot(dates, obs_lows, label='实测低温', marker='o', color='blue', linestyle='-', linewidth=2)

    # 绘制预报数据（虚线）
    plt.plot(dates, pred_highs, label='预报高温', marker='s', color='orange', linestyle='--', linewidth=2)
    plt.plot(dates, pred_lows, label='预报低温', marker='s', color='cyan', linestyle='--', linewidth=2)

    # 绘制历史均值数据（点划线）
    plt.plot(dates, hist_highs, label='历史高温均值', marker='^', color='darkred', linestyle=':', linewidth=2)
    plt.plot(dates, hist_lows, label='历史低温均值', marker='v', color='darkblue', linestyle=':', linewidth=2)

    # 图表标题和标签
    plt.title(f'{name} 温度趋势对比', fontproperties=font_prop)
    plt.xlabel('日期（月日）', fontproperties=font_prop)
    plt.ylabel('温度 (℃)', fontproperties=font_prop)
    plt.grid(True, alpha=0.3)

    # 优化显示
    plt.legend(prop=font_prop, loc='best', ncol=3)
    plt.xticks(rotation=45)
    plt.tight_layout()
    img_path=os.path.join(output_path,f"{name}.png")
    # 保存图像
    os.makedirs(output_path, exist_ok=True)
    plt.savefig(img_path, dpi=300, bbox_inches='tight')
    plt.close()
    return img_path